package com.ezgo.erc.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ezgo.erc.dao.ISyslogDao;
import com.ezgo.erc.entity.Syslog;
import com.ezgo.erc.master.utils.Constants;
import com.ezgo.erc.master.utils.GlobeStatus;
import com.ezgo.erc.master.utils.Message;
import com.ezgo.erc.master.utils.Page;

/**
 * 航线业务逻辑层
 * 
 * @author jyx
 * 
 * @date 2015-08-06
 *
 */
@Service
public class SyslogServiceImpl extends BaseServiceImpl implements SyslogService {

	@Autowired
	private ISyslogDao syslogDao;

	@Override
	public Message<List<Syslog>> getSyslog(Map<String, Object> map) {
		Message<List<Syslog>> mess = new Message<List<Syslog>>();
		String jsonStr = null;
		StringBuilder cacheKey = new StringBuilder(Constants.CACHE_SYSLOG).append(map.get("id") != null ? map.get("id") : "").append(
				map.get("type") != null ? map.get("type") : "");
		try {
			if (cacheService.exists(cacheKey.toString())) {
				jsonStr = cacheService.get(cacheKey.toString());
				mess = JSON.parseObject(jsonStr, new TypeReference<Message<List<Syslog>>>() {
				});
			} else {
				List<Syslog> syslogList = syslogDao.query(map);
				if (syslogList != null && syslogList.size() > 0) {
					mess.setStatus(GlobeStatus.API_OK.statusCode);
					mess.setMsg(GlobeStatus.API_OK.zhStatusMsg);
				} else {
					mess.setStatus(GlobeStatus.API_NOT_FOUND.statusCode);
					mess.setMsg(GlobeStatus.API_NOT_FOUND.zhStatusMsg);
				}
				mess.setData(syslogList);
				jsonStr = JSON.toJSONString(mess);
				cacheService.set(cacheKey.toString(), jsonStr, Constants.CACHE_BASIC_LIVETIME);
			}
		} catch (Exception e) {
			logger.error(String.format(Constants.EX_FORMAT_STR, this.getClass().getName(), e.getMessage()));
			mess.setStatus(GlobeStatus.API_INTER_ERROR.statusCode);
			mess.setMsg(GlobeStatus.API_INTER_ERROR.zhStatusMsg);
			mess.setData(new ArrayList<Syslog>());
		}
		return mess;
	}

	@Override
	public Syslog getSyslog(Long id) {
		return syslogDao.queryOne(id);
	}

	@Override
	public Page<Syslog> find(Page<Syslog> page, Map<String, Object> map) {
		RowBounds pageBounds = new RowBounds((page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());
		page.setList(syslogDao.getData(pageBounds, map));
		page.setCount(syslogDao.getTotalCount(map));
		return page;
	}

}
